﻿using System;
using System.Web;
using log4net;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;

namespace NhJump.Persistence.Context.HttpContextBinding
{
    /// <summary>
    /// Associates a Unit Of Work with the lifetime of an Http request
    /// </summary>
    public class BoundNHibernateUnitOfWorkModule : IHttpModule
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(BoundNHibernateUnitOfWorkModule));
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            Logger.Debug("Linking events BeginRequest and EndRequest.");
            try
            {
                context.BeginRequest += (sender, args) => UnitOfWorkFactory.Current.BuildAutoBoundUnitOfWork();
                context.EndRequest += (sender, args) =>
                {
                    UnitOfWorkBinder.CurrentUnitOfWork.Commit();
                    UnitOfWorkBinder.CurrentUnitOfWork.Dispose();
                };
            }
            catch (Exception)
            {
                Logger.Debug("Error wiring up events.");
                throw;
            }
        }
    }
}
